package com.farmer.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.farmer.common.entity.User;
import com.farmer.common.result.Result;
import com.farmer.common.utils.PasswordEncoder;
import com.farmer.user.mapper.UserMapper;
import com.farmer.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户服务实现类
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public Result<?> getUserInfo(Long userId) {
        try {
            if (userId == null) {
                return Result.error("用户ID不能为空");
            }

            User user = userMapper.selectById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }

            // 不返回密码
            user.setPassword(null);

            return Result.success("获取用户信息成功", user);
        } catch (Exception e) {
            log.error("获取用户信息失败：{}", e.getMessage(), e);
            return Result.error("获取用户信息失败");
        }
    }

    @Override
    public Result<?> updateUser(User user) {
        try {
            if (user == null || user.getId() == null) {
                return Result.error("用户信息不能为空");
            }

            // 不允许更新密码、用户名、角色等敏感信息
            User updateUser = new User();
            updateUser.setId(user.getId());
            updateUser.setNickname(user.getNickname());
            updateUser.setPhone(user.getPhone());
            updateUser.setEmail(user.getEmail());
            updateUser.setAvatar(user.getAvatar());
            updateUser.setGender(user.getGender());
            updateUser.setAge(user.getAge());
            updateUser.setAddress(user.getAddress());
            updateUser.setUpdateTime(LocalDateTime.now());

            int result = userMapper.updateById(updateUser);
            if (result > 0) {
                return Result.success("更新用户信息成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("更新用户信息失败：{}", e.getMessage(), e);
            return Result.error("更新用户信息失败");
        }
    }

    @Override
    public Result<?> getUserList(Integer pageNum, Integer pageSize, String keyword) {
        try {
            Page<User> page = new Page<>(pageNum, pageSize);
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();

            if (StringUtils.hasText(keyword)) {
                queryWrapper.like("username", keyword)
                        .or()
                        .like("nickname", keyword)
                        .or()
                        .like("phone", keyword);
            }

            // 按创建时间倒序
            queryWrapper.orderByDesc("create_time");

            Page<User> userPage = userMapper.selectPage(page, queryWrapper);

            // 清除密码信息
            userPage.getRecords().forEach(user -> user.setPassword(null));

            Map<String, Object> result = new HashMap<>();
            result.put("records", userPage.getRecords());
            result.put("total", userPage.getTotal());
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);

            return Result.success("获取用户列表成功", result);
        } catch (Exception e) {
            log.error("获取用户列表失败：{}", e.getMessage(), e);
            return Result.error("获取用户列表失败");
        }
    }

    @Override
    public Result<?> updateUserStatus(Long userId, Integer status) {
        try {
            if (userId == null || status == null) {
                return Result.error("参数不能为空");
            }

            if (status != 0 && status != 1) {
                return Result.error("状态值无效");
            }

            User user = new User();
            user.setId(userId);
            user.setStatus(status);
            user.setUpdateTime(LocalDateTime.now());

            int result = userMapper.updateById(user);
            if (result > 0) {
                String statusText = status == 1 ? "启用" : "禁用";
                return Result.success("用户" + statusText + "成功");
            } else {
                return Result.error("操作失败");
            }
        } catch (Exception e) {
            log.error("更新用户状态失败：{}", e.getMessage(), e);
            return Result.error("更新用户状态失败");
        }
    }

    @Override
    public Result<?> adminUpdateUser(User user) {
        try {
            if (user == null || user.getId() == null) {
                return Result.error("用户信息不能为空");
            }

            // 检查用户是否存在
            User existUser = userMapper.selectById(user.getId());
            if (existUser == null) {
                return Result.error("用户不存在");
            }

            // 检查用户名是否重复（如果更新了用户名）
            if (StringUtils.hasText(user.getUsername()) && !user.getUsername().equals(existUser.getUsername())) {
                QueryWrapper<User> usernameQuery = new QueryWrapper<>();
                usernameQuery.eq("username", user.getUsername());
                usernameQuery.ne("id", user.getId());
                User duplicateUser = userMapper.selectOne(usernameQuery);
                if (duplicateUser != null) {
                    return Result.error("用户名已存在");
                }
            }

            // 检查邮箱是否重复（如果更新了邮箱）
            if (StringUtils.hasText(user.getEmail()) && !user.getEmail().equals(existUser.getEmail())) {
                QueryWrapper<User> emailQuery = new QueryWrapper<>();
                emailQuery.eq("email", user.getEmail());
                emailQuery.ne("id", user.getId());
                User duplicateUser = userMapper.selectOne(emailQuery);
                if (duplicateUser != null) {
                    return Result.error("邮箱已存在");
                }
            }

            // 如果更新密码，需要加密
            if (StringUtils.hasText(user.getPassword())) {
                user.setPassword(PasswordEncoder.encode(user.getPassword()));
            } else {
                // 如果密码为空，保持原密码不变
                user.setPassword(null);
            }

            user.setUpdateTime(LocalDateTime.now());

            int result = userMapper.updateById(user);
            if (result > 0) {
                log.info("管理员更新用户信息成功，用户ID：{}", user.getId());
                return Result.success("更新用户信息成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            log.error("管理员更新用户信息失败：{}", e.getMessage(), e);
            return Result.error("更新用户信息失败");
        }
    }
} 